package cn.kgc.springmvc02.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: mosin
 * @version: v1.0  2022/12/14
 * springmvc中文件上传
 */
@Controller
@RequestMapping("file")
public class FileUploadController {


    @RequestMapping("upload")
    @ResponseBody
    public Map upload(@RequestParam("file") MultipartFile multipartFile) {
        HashMap<String, Object> map = new HashMap<>();
        // 判定文件是否为空
        if (multipartFile.isEmpty()) {
            map.put("cod", 500);
            map.put("msg", "文件不能为空");
            return map;
        }
        //获取文件名   a.txt
        String originalFilename = multipartFile.getOriginalFilename();
        //获取文件的后缀  txt
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        // 生成uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 拼接上传文件的名字
        String lastName = uuid+"."+filenameExtension;

        //文件上传
        File file = new File("D:/upload", lastName);
        try {
            multipartFile.transferTo(file);
            map.put("cod", 200);
            map.put("msg", "文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            map.put("cod", 500);
            map.put("msg", "文件上传失败");
        }

        return map;
    }


}
